package com.lemon.smartsafetynew.ui.fragment.monitor;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafetynew.entity.electrical.ElectricalCompanyVo;
import com.lemon.smartsafetynew.entity.monitor.MonitorVideoDto;
import com.lemon.smartsafetynew.entity.monitor.MonitorVideoItemVo;
import com.lemon.smartsafetynew.ui.activity.video.PLMediaPlayerActivity;
import com.lemon.smartsafetynew.ui.adapter.monitor.MonitorVideoItemAdapter;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.lemon.smartsafetynew.util.user.UserTypeUtil;
import com.pili.pldroid.player.AVOptions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Andrew on 2018/1/25.
 */

public class MonitorVideoDemoFragment extends BaseFragment
        implements RecyclerTClickListener<MonitorVideoItemVo> {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.swipRefresh)
    SwipeRefreshLayout swipRefresh;
    @Bind(R.id.empty_layout)
    LinearLayout emptyLayout;
    @Bind(R.id.tips_tv)
    TextView tipsTv;

    private MonitorVideoItemAdapter mAdapter;
    private List<MonitorVideoItemVo> mDataList = new ArrayList<>();
    private static ElectricalCompanyVo companyVo = null;

    @Override
    protected void getBaseArguments() {
        Bundle bundle = getArguments();

        if (bundle != null) {
            if (bundle.containsKey(KeyConstants.KEY_ELECTRICAL_COMPANY_INFO)) {
                companyVo = (ElectricalCompanyVo) bundle.getSerializable(KeyConstants.KEY_ELECTRICAL_COMPANY_INFO);
            }
        }
    }

    public static MonitorVideoDemoFragment newInstance(ElectricalCompanyVo companyVo) {

        Bundle args = new Bundle();
        if (companyVo != null) {
            args.putSerializable(KeyConstants.KEY_ELECTRICAL_COMPANY_INFO, companyVo);
        }

        MonitorVideoDemoFragment fragment = new MonitorVideoDemoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onItemClick(MonitorVideoItemVo data, int position) {

        if (AppUtils.isNetworkAvailable(getmContext())) {
            if (AppUtils.isWifi(getmContext())) {
                liveStream(data);
            } else {
                showChooseDialog(getmContext().getResources().getString(R.string.wifi_tips), data);
            }
        } else {
            mHUDUtil.showErrorTip("网络异常，请检查网络。", new HUDUtil.CallBack() {
                @Override
                public void onCall() {

                }
            });
        }
    }

    private void liveStream(MonitorVideoItemVo data) {
        Intent intent = new Intent(getmContext(), PLMediaPlayerActivity.class);
        intent.putExtra("videoPath", "");
        intent.putExtra("titleName", data.getTitle());
        intent.putExtra("key_id", data.getId());
        intent.putExtra("mediaCodec", AVOptions.MEDIA_CODEC_SW_DECODE);
        intent.putExtra("liveStreaming", 1);
        startActivity(intent);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragement_video_list_demo;
    }

    @Override
    protected void initViews() {

        swipRefresh.setVisibility(View.VISIBLE);
        emptyLayout.setVisibility(View.GONE);

        mAdapter = new MonitorVideoItemAdapter(mDataList, this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getmContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(mAdapter);

        swipRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getVideoList();
            }
        });

        getVideoList();
    }

    private void getVideoList() {

        swipRefresh.setVisibility(View.VISIBLE);
        emptyLayout.setVisibility(View.GONE);

        LemonRequestParams params = new LemonRequestParams("");
        if (!UserTypeUtil.isGovType(AccountUtil.getUserType())) { //非政府人员使用模块
            params.put("company_id", AccountUtil.getCompanyId());
        } else {
            if (companyVo != null) {
                params.put("company_id", companyVo.getCompanyId());
            }
        }

        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(IApplication.context());
        String serverUrl = mSharedPreferencesServer.getRequestUrl(UrlInfo.GET_MONITOR_VIDEO_LIST, Constants.VIDEO_SERVER);
        //String serverUrl = "http://58.215.171.233:18080/acloud_new/dai/getAllCameraByMoblie.json";

        OkHttpUtils.post()
                .url(serverUrl)
                .params(params)
                .build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e) {
                if (swipRefresh.isRefreshing()) {
                    swipRefresh.setRefreshing(false);
                }
                getmContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (swipRefresh != null)
                            swipRefresh.setVisibility(View.GONE);
                        if (emptyLayout != null)
                            emptyLayout.setVisibility(View.VISIBLE);
                        if (tipsTv != null)
                            tipsTv.setText("网速不给力啊,请再试一次吧。");
                        //mHUDUtil.showErrorTip("网速不给力啊,请下拉刷新再试一次吧。");
                    }
                });
            }

            @Override
            public void onResponse(String response) {

                Log.e("返回onResponse", KeyConstants.URL_GET_MONITOR_VIDEO_LIST + " " + response);

                Gson gson = new Gson();
                final List<MonitorVideoDto> monitorVideoDtos = gson.fromJson(response, new TypeToken<List<MonitorVideoDto>>() {
                }.getType());


                getmContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (swipRefresh != null && swipRefresh.isRefreshing()) {
                            swipRefresh.setRefreshing(false);
                        }

                        if (monitorVideoDtos != null && monitorVideoDtos.size() == 0) {
                            if (swipRefresh != null)
                                swipRefresh.setVisibility(View.GONE);
                            if (emptyLayout != null)
                                emptyLayout.setVisibility(View.VISIBLE);
                            if (tipsTv != null)
                                tipsTv.setText(getString(R.string.organization_no_video_data));
                        } else {
                            if (swipRefresh != null)
                                swipRefresh.setVisibility(View.VISIBLE);
                            if (emptyLayout != null)
                                emptyLayout.setVisibility(View.GONE);
                        }


                        List<MonitorVideoItemVo> list = new ArrayList<>();
                        for (MonitorVideoDto monitorVideoDto : monitorVideoDtos) {
                            MonitorVideoItemVo itemVo = new MonitorVideoItemVo();
                            itemVo.setTitle(monitorVideoDto.getName());
                            itemVo.setId(monitorVideoDto.getKey_id());
                            itemVo.setImageUrl(monitorVideoDto.getPhoto());
                            itemVo.setVideoUrl("");
                            list.add(itemVo);
                        }

                        mDataList.clear();
                        mDataList.addAll(list);
                        mAdapter.notifyDataSetChanged();
                    }
                });


            }
        });

    }

    /**
     * dialog
     */
    private MaterialDialog chooseDialog;

    private void showChooseDialog(String remark, final MonitorVideoItemVo data) {
        chooseDialog = new MaterialDialog.Builder(getmContext())
                .title("提示")
                .content(remark)
                .negativeText("继续")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        liveStream(data);
                    }
                })
                .positiveText("取消")
                .show();
    }

    private void cancelDialog() {

        if (chooseDialog != null && chooseDialog.isShowing()) {
            chooseDialog.dismiss();
            chooseDialog = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        cancelDialog();
    }

    @OnClick(R.id.retry_tv)
    public void onViewClicked() {
        getVideoList();
    }

}
